import useSettingsStore from "@/store/modules/settings";
import { Color } from "tvision-color";
// 处理主题样式
export function handleThemeStyle(brandTheme) {
  const mode = useSettingsStore().sideTheme === "theme-dark" ? "dark" : "light";
  // 以主题色加显示模式作为键
  const [{ colors: newPalette, primary: brandColorIndex }] =
    Color.getColorGradations({
      colors: [brandTheme],
      step: 10,
      remainInput: false, // 是否保留输入 不保留会矫正不合适的主题色
    });
  const colorMap = generateColorMap(
    brandTheme,
    newPalette,
    mode,
    brandColorIndex
  );
  document.documentElement.style.setProperty("--td-brand-color", brandTheme);
  for (let i = 1; i <= 9; i++) {
    document.documentElement.style.setProperty(
      `--td-brand-color-${i}`,
      colorMap[`--td-brand-color-${i}`]
    );
  }
}

/**
 * 根据当前主题色、模式等情景 计算最后生成的色阶
 */
export function generateColorMap(theme, colorPalette, mode, brandColorIdx) {
  const isDarkMode = mode === "dark";

  if (isDarkMode) {
    // eslint-disable-next-line no-use-before-define
    colorPalette.reverse().map((color) => {
      const [h, s, l] = Color.colorTransform(color, "hex", "hsl");
      return Color.colorTransform([h, Number(s) - 4, l], "hsl", "hex");
    });
    brandColorIdx = 5;
    colorPalette[0] = `${colorPalette[brandColorIdx]}`;
  }

  const colorMap = {
    "--td-brand-color": colorPalette[brandColorIdx], // 主题色
    "--td-brand-color-1": colorPalette[0], // light
    "--td-brand-color-2": colorPalette[1], // focus
    "--td-brand-color-3": colorPalette[2], // disabled
    "--td-brand-color-4": colorPalette[3],
    "--td-brand-color-5": colorPalette[4],
    "--td-brand-color-6": colorPalette[5],
    "--td-brand-color-7":
      brandColorIdx > 0 ? colorPalette[brandColorIdx - 1] : theme, // hover
    "--td-brand-color-8": colorPalette[brandColorIdx], // 主题色
    "--td-brand-color-9":
      brandColorIdx > 8 ? theme : colorPalette[brandColorIdx + 1], // click
    "--td-brand-color-10": colorPalette[9],
  };
  return colorMap;
}
